import {
  checkFileSize,
  checkFileType,
  uploadHouseImage,
} from '@/services/upload';
import { PlusOutlined } from '@ant-design/icons';
import { Upload, message } from 'antd';
import { useState } from 'react';

interface ImageUploadProps {
  value?: any[];
  onChange?: (fileList: any[]) => void;
  maxCount?: number;
  listType?: 'text' | 'picture' | 'picture-card';
  disabled?: boolean;
  className?: string;
}

const ImageUpload: React.FC<ImageUploadProps> = ({
  value = [],
  onChange,
  maxCount = 5,
  listType = 'picture-card',
  disabled = false,
  className,
}) => {
  const [uploading, setUploading] = useState(false);

  // 自定义上传请求
  const customRequest = async ({ file, onSuccess, onError }: any) => {
    // 检查文件类型
    if (!checkFileType(file as File)) {
      message.error('只支持 JPG、PNG、GIF 格式的图片！');
      onError(new Error('不支持的文件格式'));
      return;
    }

    // 检查文件大小
    if (!checkFileSize(file as File, 5)) {
      message.error('图片大小不能超过 5MB！');
      onError(new Error('文件过大'));
      return;
    }

    setUploading(true);

    try {
      const response = await uploadHouseImage(file as File);

      // 创建文件对象
      const fileObj = {
        uid: file.uid,
        name: response.fileName,
        status: 'done',
        url: `http://106.53.192.143:2774/best-live-boot/common/file/preview/${response.fileUrl}`, // 使用服务器返回的 URL
        response: response,
      };

      // 更新文件列表
      const newFileList = [...value, fileObj];
      onChange?.(newFileList);

      message.success('图片上传成功！');
      onSuccess(response);
    } catch (error) {
      console.error('上传失败:', error);
      message.error('图片上传失败，请重试！');
      onError(error);
    } finally {
      setUploading(false);
    }
  };

  // 处理文件列表变化
  const handleChange = ({ fileList }: { fileList: any[] }) => {
    // 过滤掉 uploading 状态的文件，但保留 done 状态的文件
    const filteredList = fileList.filter((file) => file.status !== 'uploading');
    onChange?.(filteredList);
  };

  // 处理文件删除
  const handleRemove = (file: any) => {
    const newFileList = value.filter((item) => item.uid !== file.uid);
    onChange?.(newFileList);
  };

  // 上传按钮
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  return (
    <Upload
      className={className}
      listType={listType}
      fileList={value}
      onChange={handleChange}
      customRequest={customRequest}
      onRemove={handleRemove}
      disabled={disabled || uploading}
      maxCount={maxCount}
      showUploadList={{
        showPreviewIcon: true,
        showRemoveIcon: true,
        showDownloadIcon: false,
      }}
    >
      {value.length >= maxCount ? null : uploadButton}
    </Upload>
  );
};

export default ImageUpload;
